<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible && !assetDetailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
          <template v-slot:filter-monthName>
            <el-input
              v-model="filterInfo.query.monthNameMult"
              class="not-mongolia"
              type="input"
              :required="true"
              :disabled="true"
              :placeholder="'请选择会计期间'"
              style="width: 100%"
            >
              <template #append>
                <el-icon @click="checkFiscalPeriodStart()"
                  ><MoreFilled
                /></el-icon>
              </template>
            </el-input>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="true"
        :handle="tableInfo.handle"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-assetCode="scope">
          <span
            v-if="scope.row.assetCode"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.assetCode }}</span
          >
          <span v-else>-</span>
        </template>
      </TableContainer>
    </div>
    <Detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :tableRow="detailInfo.tableRow"
      @returnBack="getList"
    />
    <AssetCardDetail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      @returnBack="getList"
    />
    <ExcelOrPrint :excelPrint="excelPrint"></ExcelOrPrint>
    <SelectFiscalPeriod
      v-if="selectFiscalPeriodInfo.visible"
      v-model:show-dialog="selectFiscalPeriodInfo.visible"
      :api="getBaseFiscalPeriodPage"
      :save-empty="true"
      :check-box="true"
      :highlight-row="false"
      :query="selectFiscalPeriodInfo.query"
      @callback="callBackSelectFiscalPeriod"
    />
  </div>
</template>

<script setup name="assetMonthIncomeCostQuery">
import {
  getAssetMonthExpenseCostQueryPage,
  assetMonthExpenseCostQueryExcel,
} from '@/api/dataQuery.js'
import { formatDate } from '@/utils/index'
import { getBaseFiscalPeriodPage } from '@/api/base'
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)
const Detail = defineAsyncComponent(() => import('./detail'))

import { getDeptAll } from '@/api/core'

const { proxy } = getCurrentInstance()

//打印
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: assetMonthExpenseCostQueryExcel, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  list: [
    {
      slot: 'true',
      label: '月份',
      value: 'monthName',
      event: search,
    },

    {
      componentType: 'input',
      label: '资产卡片号',
      value: 'assetCode',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产名称',
      value: 'assetName',
      event: search,
    },
    {
      componentType: 'input',
      label: '厂家名称',
      value: 'brandName',
      event: search,
    },

    {
      label: '使用部门',
      value: 'useDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '管理部门',
      value: 'manageDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
  ],
  btn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('assetMonthIncomeCostQuery:exportExcel'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: null,
  data: [],
  fieldList: [],
  fieldList1: [
    {
      label: '月份',
      value: 'monthName',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'slot',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '使用部门', value: 'useDeptName' },
    { label: '管理部门', value: 'manageDeptName' },
    { label: '设备购入金额', value: 'primitiveOriginalAmount' },
    { label: '本月预计收入', value: 'estimateTreatIncome' },
    { label: '本月实际收入', value: 'incomeAmount' },
    { label: '预计检查(治疗)人次/月', value: 'estimateTreatPersonTime' },
    { label: '实际检查(治疗)人次/月', value: 'treatPersonTime' },
    {
      label: '阳性人次',
      value: 'positivePersonTime',
    },
    { label: '预计开机时长/月', value: 'estimatePowerUp' },
    {
      label: '实际开机时长(h)',
      value: 'powerUpTime',
    },
    {
      label: '本月支出',
      value: 'allCostAmount',
    },
    {
      label: '本月折旧费用',
      value: 'depreciationAmount',
    },
    {
      label: '本月维修费用',
      value: 'repairAmount',
    },
    {
      label: '本月养护费用',
      value: 'maintenanceAmount',
    },
    {
      label: '本月耗材费用',
      value: 'materialAmount',
    },
    {
      label: '本月人工费用',
      value: 'labourAmount',
    },
    {
      label: '本月房屋折旧费',
      value: 'houseDepreciationAmount',
    },
    {
      label: '本月药品费用',
      value: 'drugAmount',
    },
    {
      label: '水电费用',
      value: 'utilitiesAmount',
    },
  ],
  fieldList2: [
    {
      label: '本月净利润',
      value: 'netAmount',
    },
    {
      label: '月收益率(%)',
      value: 'incomeRate',
    },
    {
      label: '月利润率(%)',
      value: 'profitRate',
    },
    {
      label: '阳性率(%)',
      value: 'positiveRate',
    },
    {
      label: '实际使用率(%)',
      value: 'useRate',
    },
    {
      label: '投资回报期(月)',
      value: 'investPayBackPeriod',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '效益增长趋势',
        event: toDetails,
        show: proxy.$permission('assetMonthIncomeCostQuery:details'),
      },
    ],
  },
})
const detailInfo = ref({
  visible: false,
  tableRow: '',
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
const selectFiscalPeriodInfo = ref({
  visible: false,
  query: {
    fiscalType: 2,
  },
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (
                el.code === 'assetMonthIncomeCostQuery' &&
                el.url === val.url
              ) {
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
onMounted(() => {
  getBaseFiscalPeriodPage({
    curPage: 1,
    pageSize: 99,
    sort: 'create_time desc',
    fiscalType: 2
  }).then(res => {
    if(res.total && res.success) {
      let nowTime = formatDate(new Date(), 'YYYY-MM-DD')
      res.data.find(item => {
        if(new Date(item['startDate']) <= new Date(nowTime) && new Date(item['endDate']) >= new Date(nowTime)) {
          filterInfo.value.query.monthNameMult = item.name
          getCostFieldList()
        }
      })
    }
  })
  
})
function checkFiscalPeriodStart() {
  selectFiscalPeriodInfo.value.visible = true
}
function callBackSelectFiscalPeriod(data) {
  if (data && data.length) {
    filterInfo.value.query.monthNameMult = data
      .map((item) => item.name)
      .toString()
    search()
  } else {
    filterInfo.value.query.monthNameMult = ''
    search()
  }
}
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
// 获取列表
function getList() {
  tableInfo.value.api = getAssetMonthExpenseCostQueryPage
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.api = getAssetMonthExpenseCostQueryPage
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//跳转资产卡片详情
function showDetail(row) {
  if (row.assetId && row.assetId !== -2) {
    assetDetailInfo.value.id = row.assetId
    assetDetailInfo.value.visible = true
  }
}
function handleEvent(event, data) {
  if (event === 'list') {
    if (data && data.length) {
      data.forEach((item, index) => {
        data[index] = {
          ...item,
          ...item.otherCostMap,
        }
      })
    }
    tableInfo.value.data = data
  }
}
function toDetails(row) {
  detailInfo.value.tableRow = row
  detailInfo.value.visible = true
}
function getCostFieldList() {
  //获取支出项目字段
  tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
    tableInfo.value.fieldList2
  )
  let asset_cost_project =
    proxy.$store.state.permission.dict['asset_cost_project']
  if (asset_cost_project && asset_cost_project.length) {
    let fieldList = []
    asset_cost_project.forEach((item) => {
      if (item.dictType == 1) {
        fieldList.push({
          label: item.name + '(元)',
          value: item.code,
          formatter: proxy.$fn.TripartiteMethodAsset,
        })
      }
    })
    tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
      fieldList,
      tableInfo.value.fieldList2
    )
    console.log(tableInfo.value.fieldList)
    getList()
  } else {
    setTimeout(() => {
      getCostFieldList()
    }, 100)
  }
}
</script>
<style scoped></style>
